package com.we823.project.controller;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.we823.project.common.file.FileUtil;
import com.we823.project.model.common.FileModel;
import com.we823.utils.web.RequestUtil;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("tools")
public class UploaderController {
    private static final Logger logger = LoggerFactory.getLogger(UploaderController.class);

    @RequestMapping("doUpload")
    @ResponseBody
    public Model uploader(HttpServletRequest request,@RequestParam("file")MultipartFile file,Model model) {
        FileModel fileModel = null;
        logger.debug("uploader!");
        if(file!=null){
            String t = RequestUtil.getValueByParam(request,"t","images");
            String type = RequestUtil.getValueByParam(request,"type","image/");
            if(type.toLowerCase().contains("image/")){
                t= "images";
            }else{
                t="files";
            }
            String uploadPath = "/u/r/"+t+"/"+ FileUtil.getDatePath()+"/";
            logger.debug("uploadPath:{}",uploadPath);
            String realPath = request.getServletContext().getRealPath("/")+uploadPath;
            String filename = FileUtil.getFilename(file.getOriginalFilename());
            String url = uploadPath + filename;
            File file2 = new File(realPath);
            if(file2.exists()){
                file2.mkdirs();
            }
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, filename));
                logger.debug("write files to disks");
                fileModel = new FileModel(false,file,url);
            }catch (IOException ex){
                logger.debug("write files to disks has exception:{}",ex.getMessage());
                fileModel = new FileModel(true,ex.getMessage());
            }
        }else{
            logger.debug("write files to disks file null");
            fileModel = new FileModel(true,"未提交上传文件");
        }
        model.addAttribute("filestatus",fileModel);
        logger.debug("filestatus written!");
        return model;
    }

    @RequestMapping("doUploads")
    @ResponseBody
    public Model uploader(HttpServletRequest request,@RequestParam MultipartFile[] files, Model model){

        return model;
    }
}
